import { createApp, ref } from 'vue'
import CustomLoading from '../components/CustomLoading.vue'

const loadingInstance = ref(null)

export const useLoading = () => {
  const showLoading = (text = 'submitting...') => {
    if (!loadingInstance.value) {
      const loadingApp = createApp(CustomLoading)
      const mountNode = document.createElement('div')
      document.body.appendChild(mountNode)
      loadingInstance.value = loadingApp.mount(mountNode)
    }
    loadingInstance.value.show(text)
  }

  const hideLoading = () => {
    if (loadingInstance.value) {
      loadingInstance.value.hide()
      // 延迟移除DOM，确保动画完成
      setTimeout(() => {
        if (loadingInstance.value?.$el?.parentNode) {
          document.body.removeChild(loadingInstance.value.$el.parentNode)
        }
        loadingInstance.value = null
      }, 300)
    }
  }

  return {
    showLoading,
    hideLoading
  }
}